package com.kingcat.smartchair;

import static androidx.core.app.NotificationCompat.PRIORITY_MIN;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingcat.smartchair.utils.AppUtils;
import com.kingcat.smartchair.utils.DeviceUt;
import com.kingcat.smartchair.utils.Tools;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SmartChairService extends Service {

    private static final int NOTIFICATION_ID = 1;

    @Override
    public IBinder onBind(Intent intent)
    {
        return  null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        startForeground();
    }

    /**
     * 启动前台服务
     */
    private void startForeground() {
        String channelId = null;
        // 8.0 以上需要特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("kim.hsl", "ForegroundService");
        } else {
            channelId = "";
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
        Notification notification = builder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground (1, notification);
    }

    /**
     * 创建通知通道
     * @param channelId
     * @param channelName
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName){
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(chan);
        return channelId;
    }

    @Override
    public int onStartCommand(Intent intent, int flages, int startId)
    {
        Log.e("SmartChairService", "启动了");

        // 定时检查订单任务
        Runnable runnableCheckOrder = new Runnable() {
            //run方法中是定时执行的操作
            public void run() {

                // 调用接口错误次数
                int apiErr = 0;

                // 调用周期间隔秒数
                int timelate = 20;


                while(true)
                {
                    try {
                        // WEBVIEW检测
                        if(AppUtils.getAppWebViewCurrUrl() == null || AppUtils.getAppWebViewCurrUrl().equals(""))
                        {
                            Thread.sleep(timelate * 1000);
                            continue;
                        }

                        // Log.e("SmartChairService", AppUtils.getAppWebViewCurrUrl());

                        // 非解锁页 跳过检测
                        if(AppUtils.getAppWebViewCurrUrl().indexOf("unlockpage.aspx") < 0)
                        {
                            Thread.sleep(timelate * 1000);
                            continue;
                        }

                        // debug 模拟10分钟的观看
                        // Thread.sleep(600 * 1000);

                        String checkorderurl = "";
                        if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
                        {
                            checkorderurl = AppUtils.getAppContext().getString(R.string.smartchari_checkorderurl_prod);
                        }

                        if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
                        {
                            checkorderurl = AppUtils.getAppContext().getString(R.string.smartchari_checkorderurl_dev);
                        }

                        // 检测是否到期
                        String udid = DeviceUt.GetUDID(AppUtils.getAppContext());
                        String version = DeviceUt.GetVersion(AppUtils.getAppContext());
                        String res = Tools.doGET(checkorderurl + "?padNo=" + udid + "&page=unlockPage&version=" + version + "&time=" + System.currentTimeMillis());

                        // 接口返回不为空
                        if(res != null && !res.equals(""))
                        {
                            JSONObject jsonObject = JSON.parseObject(res);
                            String msn = jsonObject.getString("msn") ;
                            long times = Long.parseLong(jsonObject.getString("resultData")) ;

                            // 接口请求成功 失败复位
                            if(msn.equals("lock") || msn.equals("unlock"))
                            {
                                apiErr = 0;
                            }
                            else
                            {
                                apiErr +=1;
                                Log.e("SmartChairService", "锁定接口请求失败,失败次数: " + apiErr + " 返回内容：" + res);

                                // 接口请求三次失败则转入启动页
                                if(apiErr >= 3)
                                {
                                    goPage(false);
                                }
                            }

                            // 时间已到 转入锁定页
                            if (msn.equals("lock")) {
                                goPage(true);
                            }
                        }
                        else
                        {
                            apiErr +=1;

                            Log.e("SmartChairService", "锁定接口请求失败,失败次数: " + apiErr + " 返回内容为空");

                            // 接口请求三次失败则转入启动页
                            if(apiErr >= 3)
                            {
                                goPage(false);
                            }
                        }

                        Thread.sleep(timelate * 1000);
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                }
            }
        };

        // 开始执行定时检查订单任务
        Thread threadCheckOrder = new Thread(runnableCheckOrder);
        threadCheckOrder.start();

        // 定时上传日志任务
        Runnable runnablePostLog = new Runnable() {
            //run方法中是定时执行的操作
            public void run() {

                // 检测强制重启任务
                try
                {
                    String udid = DeviceUt.GetUDID(AppUtils.getAppContext());

                    String checkrebooturl = "";
                    if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
                    {
                        checkrebooturl = AppUtils.getAppContext().getString(R.string.smartchari_checkrebooturl_prod);
                    }

                    if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
                    {
                        checkrebooturl = AppUtils.getAppContext().getString(R.string.smartchari_checkrebooturl_dev);
                    }

                    // 检测是否有强制重启
                    String res = Tools.doGET(checkrebooturl + "?padNo=" + udid + "&time=" + System.currentTimeMillis());
                    //String res = Tools.doGET("http://192.168.1.3/api/CheckReboot?padNo=" + udid + "&time=" + System.currentTimeMillis());

                    // Log.e("SmartChairService", res);
                    if(res != null && !res.equals(""))
                    {
                        JSONObject jsonObject = JSON.parseObject(res);
                        String msn = jsonObject.getString("msn") ;

                        // 如果有重启任务则强制重启机器
                        if(msn.equals("reboot"))
                        {
                            DeviceUt.rootCall("reboot");
                        }
                    }
                }
                catch (Exception ex)
                {

                }

                try
                {
                    List<ContentValues> list = SmartDatabaseHelper.QueryDeviceLog(AppUtils.getAppContext());

                    list.forEach(it -> {
                        //Log.e("-----------deviceLog", "id:" + it.get("id") + " udid:" + it.get("udid") + " page:" + it.get("page") + " time:" + it.get("time") + " cat:" + it.get("cat") + " event:" + it.get("event"));

                        it.put("eventinfo", it.get("event").toString());

                        String logposturl = "";
                        if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
                        {
                            logposturl = AppUtils.getAppContext().getString(R.string.smartchari_logposturl_prod);
                        }

                        if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
                        {
                            logposturl = AppUtils.getAppContext().getString(R.string.smartchari_logposturl_dev);
                        }

                        String res  = Tools.doPOSTObject(logposturl,it);

                        // 删除已经上传的日志数据
                        if(res.indexOf("code") > 0 && res.indexOf("200")> 0)
                        {
                            SmartDatabaseHelper.DelDeviceLog(AppUtils.getAppContext(), it.get("id").toString());
                        }
                    });
                }
                catch (Exception e)
                {
                    ContentValues model = new ContentValues();
                    model.put("udid", DeviceUt.GetUDID(AppUtils.getAppContext()));
                    model.put("page", "logpostApi");
                    model.put("time", System.currentTimeMillis());
                    model.put("cat", -1);
                    model.put("event", "调用接口异常");
                    model.put("message", e.toString());
                    SmartDatabaseHelper.AddDeviceLog(AppUtils.getAppContext(), model);
                }
            }
        };


        // 定时执行日志上传
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        // * 参数一:command：执行线程
        // * 参数二:initialDelay：初始化延时
        // * 参数三:period：两次开始执行最小间隔时间
        // * 参数四:unit：计时单位
        //service.scheduleAtFixedRate(runnablePostLog, 1, 30, TimeUnit.MINUTES);
        service.scheduleAtFixedRate(runnablePostLog, 1, 30, TimeUnit.MINUTES);
        return super.onStartCommand(intent, flages, startId);
    }

    // 转入锁定页或启动页
    private void goPage(boolean isLock)
    {
        // 日志
        ContentValues model = new ContentValues();
        model.put("udid", DeviceUt.GetUDID(AppUtils.getAppContext()));
        model.put("page", "unlockpage");
        model.put("time", System.currentTimeMillis());
        if(!isLock)
        {
            model.put("cat", -1);
            model.put("event", "订单时间检测失败");
        }
        else
        {
            model.put("cat", 0);
            model.put("event", "订单时间结束");
            model.put("message", "即将进入锁屏页");
        }
        SmartDatabaseHelper.AddDeviceLog(AppUtils.getAppContext(), model);

        // 设置为已锁定状态（防止转入过程中用户再次点击APP）
        AppUtils.setAppIsUnlock(false);

        // 关闭第三方APP
        DeviceUt.killAllApp(AppUtils.getAppContext());

        // 根据情况转到不同页面
        AppUtils.getAppWebView().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 设备号
                String udid = DeviceUt.GetUDID(AppUtils.getAppContext());

                if(isLock)
                {
                    String lockpageurl = "";
                    if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
                    {
                        lockpageurl = AppUtils.getAppContext().getString(R.string.smartchari_lockurl_prod);
                    }

                    if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
                    {
                        lockpageurl = AppUtils.getAppContext().getString(R.string.smartchari_lockurl_dev);
                    }

                    AppUtils.getAppWebView().loadUrl(lockpageurl + "?udid=" + udid + "&time=" + System.currentTimeMillis());
                }
                else {
                    AppUtils.getAppWebView().loadUrl("file:///android_asset/index.html?udid=" + udid);
                }
            }
        }, 100);
    }

    @Override
    public  void onDestroy() {
        super.onDestroy();
    }
}